package com.qidian.mespro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mespro.mapper.DictDataMapper;
import com.qidian.mespro.mapper.ProcessMapper;
import com.qidian.mespro.mapper.WorkflowProcessMapper;
import com.qidian.mespro.service.WorkflowProcessService;
import com.qidianit.mes.pojo.Process;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.WorkflowProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @ author: 周晓轩
 * @ company 起点编程
 * @ time: 2025/9/19 - 14:03
 * @ Description:
 */
@Service
public class WorkflowProcessServiceImpl implements WorkflowProcessService {

    @Autowired
    private WorkflowProcessMapper workflowProcessMapper;
    @Autowired
    private ProcessMapper processMapper;
    @Autowired
    private DictDataMapper dictDataMapper;

    @Override
    public Result<PageInfo<WorkflowProcess>> selectList(Long workflowId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        // 查询当前工艺下的所有工序关联记录
        List<WorkflowProcess> workflowProcesses = workflowProcessMapper.selectList(workflowId);

        // 遍历处理关联数据
        for (WorkflowProcess wp : workflowProcesses) {
            // 1. 查询当前工序详情
            if (wp.getProcessId() != null) {
                wp.setProcess(processMapper.selectById(wp.getProcessId())); // 需在ProcessMapper中添加selectById方法
            }

            // 2. 查询下一道工序
            List<WorkflowProcess> allProcessesInWorkflow = workflowProcessMapper.selectList(workflowId);
            wp.setNextProcess(getNextProcess(allProcessesInWorkflow, wp));

            // 3. 查询关系字典数据
            if (wp.getRelationNext() != null) {
                wp.setRelationNextDict(dictDataMapper.selectById(wp.getRelationNext()));
            }
        }

        return Result.success(new PageInfo<>(workflowProcesses));
    }


    /**
     * 根据当前工序在工艺流程中的顺序，获取下一道工序
     */
    private Process getNextProcess(List<WorkflowProcess> allProcesses, WorkflowProcess current) {
        if (allProcesses == null || allProcesses.isEmpty()) {
            return null;
        }
        // 按步骤序号排序后查找下一个
        allProcesses.sort(Comparator.comparing(WorkflowProcess::getStepOrder));
        for (int i = 0; i < allProcesses.size(); i++) {
            if (allProcesses.get(i).getId().equals(current.getId())) {
                // 存在下一个步骤
                if (i + 1 < allProcesses.size()) {
                    Long nextProcessId = allProcesses.get(i + 1).getProcessId();
                    return processMapper.selectById(nextProcessId); // 需在ProcessMapper中添加selectById方法
                }
                break;
            }
        }
        return null;
    }

    @Override
    public Result<WorkflowProcess> addWorkflowProcess(WorkflowProcess workflowProcess) {
        if (workflowProcess.getWorkflowId() == null) {
            return Result.error("工艺流程ID不能为空");
        }
        if (workflowProcess.getStepOrder() == null) {
            return Result.error("工序序号不能为空");
        }
        int count = workflowProcessMapper.countByWorkflowIdAndStepOrder(
                workflowProcess.getWorkflowId(),
                workflowProcess.getStepOrder()
        );
        if (count > 0) {
            return Result.error("当前工艺流程下已存在序号为[" + workflowProcess.getStepOrder() + "]的工序，请更换序号");
        }
        return workflowProcessMapper.addWorkflowProcess(workflowProcess)== 1?Result.success(workflowProcess):Result.error("保存失败");
    }

    @Override
    public Result<WorkflowProcess> selectWorkflowProcessById(Long id) {
        return Result.success(workflowProcessMapper.selectWorkflowProcessById(id));
    }

    @Override
    public Result updateWorkflowProcessById(WorkflowProcess workflowProcess) {
        if (workflowProcess.getId() == null) {
            return Result.error("记录ID不能为空");
        }
        if (workflowProcess.getWorkflowId() == null) {
            return Result.error("工艺流程ID（workflowId）不能为空");
        }
        if (workflowProcess.getStepOrder() == null) {
            return Result.error("工序序号（stepOrder）不能为空");
        }

        int count = workflowProcessMapper.countByWorkflowIdAndStepOrderExcludeId(workflowProcess.getWorkflowId(), workflowProcess.getStepOrder(), workflowProcess.getId());
        if (count > 0) {
            return Result.error("当前工艺流程下已存在序号为[" + workflowProcess.getStepOrder() + "]的工序，请更换序号");
        }
        return workflowProcessMapper.updateWorkflowProcessById(workflowProcess)== 1 ? Result.success():Result.error("编辑失败");
    }

    @Override
    public Result deleteWorkflowProcessById(Long id) {
        return workflowProcessMapper.deleteWorkflowProcessById(id) == 1?Result.success():Result.error("删除失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return workflowProcessMapper.batchDelete(ids) > 0?Result.success():Result.error("删除失败");
    }
}
